

 #define _PROGRAM				"VGettyAMSlave"
 #define _VERSION				"0.1"

 #define _LOCAL_ADDRESS			"192.168.0.2"
 #define _LOCAL_PORT				7902
 #define _DEVICE_ADDRESS			"192.168.0.2"
 #define _DEVICE_PORT			7901

 #define _LISTEN_WAIT_TIMEOUT	20

 #define _ACTION_SEND			"send"
 #define _ACTION_SENDWAIT		"sendwait"

//--------------------------------------------------------------------------------
 #include <QObject>
 #include <QUdpSocket>
//--------------------------------------------------------------------------------


#ifndef __UdpListener_H__
 #define __UdpListener_H__

class UdpListener : public QObject  {

 Q_OBJECT

 public:
	UdpListener() : QObject(NULL) {
		this->udpSocket = NULL;
		this->messageCount = 0;
	 }
	virtual ~UdpListener() { }

	void initSocket()
	 {
		this->udpSocket = new QUdpSocket(this);
		this->udpSocket->bind(QHostAddress::LocalHost, _LOCAL_PORT);
		connect( this->udpSocket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()) );
	 }

	void close()
	 {
		if ( this->udpSocket == NULL ) return;
		this->udpSocket->close();
		delete this->udpSocket; this->udpSocket = NULL;
	 }

 public:
	bool sendDatagram( const char* data, long size, const string& address, int port ) {
		QUdpSocket* localSocket = NULL;
		if ( this->udpSocket != NULL )
			localSocket = this->udpSocket;
		else
			localSocket = new QUdpSocket();

		qint64 size64 = size;
		QHostAddress qaddress( QString(address.c_str()) );
		bool done = ( size64 == localSocket->writeDatagram( data, size64, qaddress, port ) );

		if ( this->udpSocket != localSocket )
			delete localSocket;

		return done;
	 }

 protected slots:
	virtual void readPendingDatagrams()
	 {
		QByteArray datagram;
		QHostAddress sender;
		quint16 senderPort;
		while( this->udpSocket->hasPendingDatagrams() ) {
			datagram.resize(this->udpSocket->pendingDatagramSize());
			this->udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
			this->retData = string(datagram.data());
			this->messageCount++;
		 }
	 }

 public:
	string retData;
	int messageCount;
	QUdpSocket* udpSocket;

};


#endif //__UdpListener_H__
